package com.idanchuang.component.mq.amqp.rabbit;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author yjy
 * Created at 2022/3/23 1:56 下午
 */
public class SimpleSender {

    public static void main(String[] args) throws Exception {
        // 通过ConnectionFactory创建Connection
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUsername("dc_base");
        connectionFactory.setPassword("JFgs33#s3");
        connectionFactory.setHost("10.80.20.209");
        connectionFactory.setVirtualHost("/");
        Connection connection = connectionFactory.newConnection();

        // 声明交换机
        String exchange = "python-test-exchange";
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(exchange, "direct");

        // 路由键
        String routingKey = "tester";

        final Semaphore semaphore = new Semaphore(0);
        final AtomicBoolean success = new AtomicBoolean();

        // 给管道设置消息发送成功确认监听器
        channel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                success.set(true);
                semaphore.release();
            }
            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                success.set(false);
                semaphore.release();
            }
        });
        // 发送消息前告知服务端，回调下一个消息的发送结果
        channel.confirmSelect();
        // 发送消息
        channel.basicPublish(exchange, routingKey, null, "hello world1!".getBytes(StandardCharsets.UTF_8));
        // 等待结果
        semaphore.acquire();
        System.out.println("消息发送 > " + (success.get() ? "成功" : "失败"));

        // 再来一次
        channel.confirmSelect();
        channel.basicPublish(exchange, routingKey, null, "hello world2!".getBytes(StandardCharsets.UTF_8));
        semaphore.acquire();
        System.out.println("消息发送 > " + (success.get() ? "成功" : "失败"));

        // 结束
        connection.close();
    }

}
